package com.wenchao.serialport;

import android.content.Context;
import android.content.Intent;
import android.util.Log;

import com.example.x6.serial.SerialPort;

/**
 * 【类的描述】介绍一下该类的用途
 *
 * @author zhangwenchao
 * @date 2021-12-29
 */
public class SerialPortReadThread extends Thread {

    private static final String TAG = SerialPortReadThread.class.getSimpleName();

    private Context mContext;
    private final SerialPort serialPort;
    private final byte[] mReadBuffer;

    public SerialPortReadThread(Context context, SerialPort serialPort) {
        mContext = context;
        this.serialPort = serialPort;
        mReadBuffer = new byte[1024];
    }

    @Override
    public void run() {
        super.run();

        while (true) {
            if (serialPort.getInputStream() == null) {
                return;
            }

            int size = serialPort.readData(mReadBuffer);
            if (size == 0) {
                try {
                    sleep(100);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                continue;
            }

            byte[] readBytes = new byte[size];
            System.arraycopy(mReadBuffer, 0, readBytes, 0, size);
            Log.d(TAG, ByteUtils.bytesToHexString(readBytes));

            Intent intent = new Intent();
            // 设置intent的动作为com.example.broadcast，可以任意定义
            intent.setAction(SerialPortService.RECEIVER_ACTION_NAME);
            intent.putExtra("data", readBytes);
            // 发送无序广播
            mContext.sendBroadcast(intent);
        }
    }

}
